package com.member.web.controller.shop;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.enums.ScopeUseEnum;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.http.HttpUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.SysBizCoupon;
import com.member.shop.domain.SysBizCouponGrant;
import com.member.shop.domain.SysBizUser;
import com.member.shop.dto.ExternalCouponDto;
import com.member.shop.dto.SysBizCouponSendDto;
import com.member.shop.mapper.SysBizCouponMapper;
import com.member.shop.service.ISysBizCouponGrantService;
import com.member.shop.service.ISysBizCouponReceiveService;
import com.member.shop.service.ISysBizCouponService;
import com.member.shop.service.ISysBizUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 【优惠券规则】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-05-08
 **/
@RestController
@RequestMapping("/shop/coupon")
public class SysBizCouponController extends BaseController {
    @Resource
    private ISysBizCouponService sysBizCouponService;

    @Resource
    private ISysBizCouponReceiveService sysBizCouponReceiveService;

    @Resource
    private ISysBizCouponGrantService sysBizCouponGrantService;


    @Resource
    private ISysBizUserService sysBizUserService;

    /**
     * 查询优惠券规则列表
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizCoupon sysBizCoupon) {
        setTenantId(sysBizCoupon);
        startPage();
        LambdaQueryWrapper<SysBizCoupon> queryWrapper = new LambdaQueryWrapper<SysBizCoupon>();
        queryWrapper.eq((sysBizCoupon.getTenantId() != null && sysBizCoupon.getTenantId() > 0), SysBizCoupon::getTenantId, sysBizCoupon.getTenantId());
        queryWrapper.eq(sysBizCoupon.getDisplayed() != null, SysBizCoupon::getDisplayed, sysBizCoupon.getDisplayed());
        queryWrapper.like(StringUtils.isNotEmpty(sysBizCoupon.getName()), SysBizCoupon::getName, sysBizCoupon.getName());
        queryWrapper.eq(sysBizCoupon.getNewCoupon() != null, SysBizCoupon::getNewCoupon, sysBizCoupon.getNewCoupon());
        queryWrapper.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        queryWrapper.orderByDesc(SysBizCoupon::getCreateTime);
        List<SysBizCoupon> list = sysBizCouponService.selectSysBizCouponList(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            for (SysBizCoupon bizCoupon : list) {
                Long usedNumCoupon = sysBizCouponService.getUsedNumCoupon(bizCoupon.getId());
                bizCoupon.setUsedNum(usedNumCoupon);

            }
        }

        return getDataTable(list);
    }

    private void setTenantId(SysBizCoupon sysBizCoupon) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizCoupon.setTenantId(tenantId);
        }
    }

    @PreAuthorize("@ss.hasPermi('shop:coupon:list')")
    @GetMapping("/listCouponByListId/{ids}")
    public  List<SysBizCoupon> listCouponByListId(@PathVariable Long[] ids) {
        // 校验 ids 是否为空
        if (ids == null || ids.length == 0) {
            return Collections.emptyList();
        }
        List<Long> list1 = Arrays.asList(ids);
        List<SysBizCoupon> list = sysBizCouponService.selectSysBizCouponList(
                new LambdaQueryWrapper<SysBizCoupon>()
                .in(SysBizCoupon::getId, list1));
        if (!CollectionUtils.isEmpty(list)) {
            for (SysBizCoupon bizCoupon : list) {
                Long usedNumCoupon = sysBizCouponService.getUsedNumCoupon(bizCoupon.getId());
                bizCoupon.setUsedNum(usedNumCoupon);

            }
        }

        return list;
    }

    @PreAuthorize("@ss.hasPermi('shop:coupon:list')")
    @GetMapping("/list2")
    public TableDataInfo list2(SysBizCoupon sysBizCoupon) {
//        LambdaQueryWrapper<SysBizCoupon> queryWrapper = new LambdaQueryWrapper<SysBizCoupon>();
//        queryWrapper.and(wrapper -> wrapper
//                .eq(SysBizCoupon::getValidityType, 1)
//                .lt(SysBizCoupon::getTermEndTime, DateUtil.now())
//        ).or().eq(SysBizCoupon::getValidityType, 2);
//        queryWrapper.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
//        queryWrapper.orderByDesc(SysBizCoupon::getCreateTime);
        setTenantId(sysBizCoupon);
        List<SysBizCoupon> list = sysBizCouponService.list2(sysBizCoupon);
//        if (!CollectionUtils.isEmpty(list)) {
//            for (SysBizCoupon bizCoupon : list) {
//                Long usedNumCoupon = sysBizCouponService.getUsedNumCoupon(bizCoupon.getId());
//                bizCoupon.setUsedNum(usedNumCoupon);
//
//            }
//        }

        return getDataTable(list);
    }

    /**
     * 导出优惠券规则列表
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:export')")
    @Log(title = "优惠券规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizCoupon sysBizCoupon) {
        LambdaQueryWrapper<SysBizCoupon> queryWrapper = new LambdaQueryWrapper<SysBizCoupon>();
        List<SysBizCoupon> list = sysBizCouponService.selectSysBizCouponList(queryWrapper);
        ExcelUtil<SysBizCoupon> util = new ExcelUtil<SysBizCoupon>(SysBizCoupon.class);
        util.exportExcel(response, list, "优惠券规则数据");
    }

    /**
     * 获取优惠券规则详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysBizCouponService.selectSysBizCouponById(id));
    }

    /**
     * 新增优惠券规则
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:add')")
    @Log(title = "优惠券规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizCoupon sysBizCoupon) {
        LambdaQueryWrapper<SysBizCoupon> sysBizCouponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizCouponLambdaQueryWrapper.eq(SysBizCoupon::getName, sysBizCoupon.getName());
        sysBizCouponLambdaQueryWrapper.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        if (!sysBizCouponService.selectSysBizCouponList(sysBizCouponLambdaQueryWrapper).isEmpty()) {
            return AjaxResult.warn("该优惠券名称已存在");
        }

        if (sysBizCoupon.getNewCoupon() == 1) {
            LambdaQueryWrapper<SysBizCoupon> sysBizCouponLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            sysBizCouponLambdaQueryWrapper2.eq(SysBizCoupon::getNewCoupon, 1);
            sysBizCouponLambdaQueryWrapper2.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            sysBizCouponLambdaQueryWrapper2.eq(SysBizCoupon::getTenantId, sysBizCoupon.getTenantId());
            if (!CollectionUtils.isEmpty(sysBizCouponService.selectSysBizCouponList(sysBizCouponLambdaQueryWrapper2))) {
                return AjaxResult.warn("新人优惠券已存在");
            }
        }
        return toAjax(sysBizCouponService.insertSysBizCoupon(sysBizCoupon));
    }

    /**
     * 修改优惠券规则
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:edit')")
    @Log(title = "优惠券规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizCoupon sysBizCoupon) {
        LambdaQueryWrapper<SysBizCoupon> sysBizCouponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizCouponLambdaQueryWrapper.eq(SysBizCoupon::getName, sysBizCoupon.getName());
        sysBizCouponLambdaQueryWrapper.ne(SysBizCoupon::getId, sysBizCoupon.getId());
        sysBizCouponLambdaQueryWrapper.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        if (!sysBizCouponService.selectSysBizCouponList(sysBizCouponLambdaQueryWrapper).isEmpty()) {
            return AjaxResult.warn("该优惠券名称已存在");
        }
        //编辑优惠券总数时，调整的数量不能在已领取的数值以下
        if (sysBizCoupon.getTotalNum() < sysBizCoupon.getIssueNum()) {
            return AjaxResult.warn("优惠券总数量不能在低于已领取的数量");
        }

        if (sysBizCoupon.getNewCoupon() == 1) {
            LambdaQueryWrapper<SysBizCoupon> sysBizCouponLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            sysBizCouponLambdaQueryWrapper2.eq(SysBizCoupon::getNewCoupon, 1);
            sysBizCouponLambdaQueryWrapper2.ne(SysBizCoupon::getId, sysBizCoupon.getId());
            sysBizCouponLambdaQueryWrapper2.eq(SysBizCoupon::getTenantId, sysBizCoupon.getTenantId());
            sysBizCouponLambdaQueryWrapper2.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            if (!CollectionUtils.isEmpty(sysBizCouponService.selectSysBizCouponList(sysBizCouponLambdaQueryWrapper2))) {
                return AjaxResult.warn("新人优惠券已存在");
            }
        }


        return toAjax(sysBizCouponService.updateSysBizCoupon(sysBizCoupon));
    }

    /**
     * 删除优惠券规则
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:remove')")
    @Log(title = "优惠券规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(sysBizCouponService.deleteSysBizCouponById(id));
    }


    /**
     * 优惠券根据用户发放
     */
    @PreAuthorize("@ss.hasPermi('shop:coupon:add')")
    @Log(title = "优惠券规则", businessType = BusinessType.INSERT)
    @PostMapping("/send")
    public AjaxResult send(@RequestBody SysBizCouponSendDto sysBizCouponSendDto) {
        try {
            Long userId = sysBizCouponSendDto.getUserId();
            SysBizUser byId = sysBizUserService.getById(userId);

            List<SysBizCoupon> sysBizCoupon = sysBizCouponSendDto.getSysBizCoupon();
            int rows = sysBizCouponGrantService.SysBizCouponGrantByUser(sysBizCoupon,byId.getUserPhone());
            return toAjax(rows);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }



    @Value("${coupon.urlOld}")
    private String couponUrlOld;


    /**
     * 优惠券同步
     */
    @RequestMapping("/syncCoupons")
    public AjaxResult syncCoupons() {
        String couponUrlOldStr = HttpUtils.sendGet(couponUrlOld);

        // 解析响应
        com.alibaba.fastjson2.JSONObject jsonResponse = JSON.parseObject(couponUrlOldStr);
        int code = jsonResponse.getIntValue("code");

        if(code!=200){
            return AjaxResult.warn("优惠券同步失败");
        }
        String jsonArrayString = jsonResponse.getString("data");
        List<ExternalCouponDto> externalCouponDtoList = JSON.parseArray(jsonArrayString, ExternalCouponDto.class);

        List<SysBizCoupon> sysBizCouponArrayList = new ArrayList<SysBizCoupon>();
        for (ExternalCouponDto externalCouponDto : externalCouponDtoList) {
            if (StringUtils.isEmpty(externalCouponDto.getCode())) {
                continue;
            }
            List<SysBizCoupon> sysBizCoupons = sysBizCouponService.selectSysBizCouponList(new LambdaQueryWrapper<SysBizCoupon>()
                    .eq(SysBizCoupon::getUid, externalCouponDto.getCode())
                    .eq(SysBizCoupon::getTenantId, 2L)
                    .eq(SysBizCoupon::getDeleted, 0));
            if(!CollectionUtils.isEmpty(sysBizCoupons)){
                continue;
            }
            SysBizCoupon sysBizCoupon = new SysBizCoupon();
            sysBizCoupon.setTenantId(2L);
            sysBizCoupon.setUid(externalCouponDto.getCode());
            sysBizCoupon.setName(externalCouponDto.getTitle());
            sysBizCoupon.setValidityType(externalCouponDto.getDateType());
            sysBizCoupon.setThresholdAmount(new BigDecimal(externalCouponDto.getGetlimit()));
            sysBizCoupon.setDiscountValue(new BigDecimal(externalCouponDto.getCouponVal()));
            if (externalCouponDto.getDateType() == 1) {
                sysBizCoupon.setTermBeginTime(externalCouponDto.getOnDate());
                sysBizCoupon.setTermEndTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, externalCouponDto.getOffDate()) + " 23:59:59"));
                sysBizCoupon.setReceivingDay(null);
                sysBizCoupon.setEffectiveDay(null);
            } else if (externalCouponDto.getDateType() == 2) {
                sysBizCoupon.setTermBeginTime(null);
                sysBizCoupon.setTermEndTime(null);
                sysBizCoupon.setReceivingDay(0L);
                sysBizCoupon.setEffectiveDay(Long.valueOf(externalCouponDto.getDayLen().trim()));
            }

            sysBizCoupon.setTotalNum(99999999L);
            sysBizCoupon.setSurplusNum(99999999L);
            sysBizCoupon.setUserLimit((long) externalCouponDto.getNumber());
            sysBizCoupon.setScopeUse(ScopeUseEnum.ALL_GOODS.getKey());
            sysBizCoupon.setOrderNum(50L);
            sysBizCoupon.setCouponDescription(externalCouponDto.getSubTitle());
            sysBizCoupon.setCreateTime(DateUtils.getNowDate());
            sysBizCouponArrayList.add(sysBizCoupon);
        }
        sysBizCouponService.saveBatch(sysBizCouponArrayList);

        return AjaxResult.success();
    }
}
